package ui.activity.card;

import java.util.List;

import ui.model.IOnViewModelUpated;
import ui.model.ModelErrorInfo;
import ui.model.ViewModel;
import ui.model.card.EditCardViewModel;
import util.cardparse.ParseCardHelper;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
import business.entity.Card;
import business.service.card.IEditCardViewService;
import business.service.card.impl.EditCardViewService;

import com.google.gson.JsonSyntaxException;
import com.lab107team.R;


public class EditCardActivity extends Activity implements OnClickListener, DialogInterface.OnClickListener {

	private static final String TAG = EditCardActivity.class.getSimpleName();

	private EditCardViewModel model;
	private IEditCardViewService service;

	private AlertDialog.Builder mBuilder;
	private OnViewModelUpdated mListener;

	private boolean isAdd = false;
	private int id;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.edit_card_activity_layout);
		
		initilizeWidget();
		
		model = new EditCardViewModel();
		service = new EditCardViewService(model);

		mListener = new OnViewModelUpdated();
		model.addListener(mListener);
		
		Intent intent = getIntent();
		if (intent != null) {
			isAdd = intent.getBooleanExtra("isAdd", false);
			Log.i(TAG, "是否添加名片 -> " + isAdd);
		} else {
			Log.i(TAG, "intent = null");
		}

		if (isAdd) {
			id = -1;
			Card card = null;
			if (intent.getStringExtra("msg") == null) {
				model.setCard(new Card());
			} else {
				String msg = intent.getStringExtra("msg");
				try {
					card = ParseCardHelper.decodeCard(msg);
					Log.i(TAG, "解析二维码名片成功");
					model.setCard(card);
				} catch (JsonSyntaxException e) {
					Log.e(TAG, "解析二维码名片失败");
				}
			}

		} else {
			id = intent.getIntExtra("id", -1);
			Card card = null;
			card = service.search(id);
			model.setCard(card);
		}
		
		Card card = model.getCard();
		if (card == null) {
			Log.i(TAG, "要编辑的名片信息不存在");
			finish();
			return;
		}

		((EditText) findViewById(R.id.et_edit_card_name)).setText(card.getName());
		((EditText) findViewById(R.id.et_edit_card_telephone)).setText(card.getTelephone());
		((EditText) findViewById(R.id.et_edit_card_email)).setText(card.getEmail());
		((EditText) findViewById(R.id.et_edit_card_qq)).setText(card.getQq());
		((EditText) findViewById(R.id.et_edit_card_weibo)).setText(card.getWeibo());
		((Button) findViewById(R.id.btn_edit_card_del)).setVisibility(isAdd ? View.GONE : View.VISIBLE);
	}

	private void initilizeWidget() {
		mBuilder = new Builder(this)
				.setTitle("提示")
				.setMessage("确认删除该名片吗?")
				.setPositiveButton("确认", this)
				.setNegativeButton("取消", this);

		((Button) findViewById(R.id.btn_edit_card_del)).setOnClickListener(this);
		((ImageButton) findViewById(R.id.btn_edit_card_sure)).setOnClickListener(this);
		((ImageButton) findViewById(R.id.btn_edit_card_back)).setOnClickListener(this);
	}

	protected void updateView(ViewModel aVM) { }

	
	private class OnViewModelUpdated implements IOnViewModelUpated {

		@Override
		// 视图模型更新后的回调方法
		public void onUpdated(ViewModel vm) {
			updateView(vm);
		}

		@Override
		// 发现视图模型错误时的回调方法
		public void onViewModelInError(List<ModelErrorInfo> errsOfVM) {
			String errTxt = "";

			for (int i = 0; i < errsOfVM.size(); i++) {
				errTxt += errsOfVM.get(i).getErrMsg() + "\n";
			}
            //调用子类的处理视图模型错误方法
			processViewModelErrorMsg(errsOfVM, errTxt);
		}

	}
	
	protected void processViewModelErrorMsg(List<ModelErrorInfo> errsOfVM, String errMsg) {
		ModelErrorInfo errorInfo = errsOfVM.get(0);
		Toast.makeText(EditCardActivity.this, errorInfo.getErrMsg(), Toast.LENGTH_SHORT).show();
	}

	@Override
	protected void onDestroy() {
		if (model != null) {
			int position = model.findListener(mListener);
			if (position > -1) {
				model.removeListener(mListener);
			}
		}
		super.onDestroy();
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_edit_card_back:
			onBackBtnClick(v);
			break;

		case R.id.btn_edit_card_sure:
			onSureBtnClick(v);
			break;

		case R.id.btn_edit_card_del:
			onDelBtnClick(v);
			break;

		default:
			break;
		}
	}

	private void onBackBtnClick(View v) {
		if (!isAdd) {
			EditCardViewModel editCardViewModel = (EditCardViewModel) model;
			Intent intent = new Intent(EditCardActivity.this, CardDetailActivity.class);
			id = editCardViewModel.getCard().getId();
			intent.putExtra("id", id);
			startActivity(intent);
		}
		finish();
	}

	private void onSureBtnClick(View v) {
		Log.i(TAG, "确认按钮被点击");

		Card card = model.getCard();

		card.setName(((EditText) findViewById(R.id.et_edit_card_name)).getText().toString().trim());
		card.setTelephone(((EditText) findViewById(R.id.et_edit_card_telephone)).getText().toString().trim());
		card.setEmail(((EditText) findViewById(R.id.et_edit_card_email)).getText().toString().trim());
		card.setQq(((EditText) findViewById(R.id.et_edit_card_qq)).getText().toString().trim());
		card.setWeibo(((EditText) findViewById(R.id.et_edit_card_weibo)).getText().toString().trim());

		boolean isLegal = false;
		if (isAdd) {
			isLegal = service.add(card);
		} else {
			isLegal = service.save(card);
		}
		
		// 没抛出异常就说明执行成功, 接着判断是否合法
		if (isLegal) {
			if (!isAdd) {
				Intent intent = new Intent(EditCardActivity.this, CardDetailActivity.class);
				id = model.getCard().getId();
				intent.putExtra("id", id);
				startActivity(intent);
			}
			finish();
		}
	}

	private void onDelBtnClick(View v) {
		(mBuilder.create()).show();
	}

	@Override
	public void onClick(DialogInterface dialog, int which) {
		switch (which) {
		case DialogInterface.BUTTON_POSITIVE:
			onSureDelBtnClick(dialog);
			break;

		case DialogInterface.BUTTON_NEGATIVE:
			onCancelDelBtnClick(dialog);
			break;

		default:
			break;
		}
	}
	
	private void onSureDelBtnClick(DialogInterface dialog) {
		EditCardViewModel editCardViewModel = (EditCardViewModel) model;
		Card card = editCardViewModel.getCard();
		int id = card.getId();
		service.delete(id);
		dialog.dismiss();
		finish();
	}

	private void onCancelDelBtnClick(DialogInterface dialog) {
		dialog.dismiss();		
	}

}
